<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue 路由hash实现原理</title>
    <style>.active{color:red} #home,#about{display: none;}</style>
<body>
    <div id="app">
        <p> <a href="#/home">首页</a> | <a href="#/about">关于</a> | <button onclick="location.hash='#/home'">首页</button> </p>
        <div id="home">
            <h1>首页内容</h1>
        </div>
        <div id="about">
            <h1>关于我们内容</h1>
        </div>
    </div>
    
    <script> 
// 文档加载完毕 获取hash值
document.addEventListener("DOMContentLoaded",e=>{
    let hash = location.hash || "#/home"; 
    // 获取hash值默认为home（首页）
    if(hash==="#/home"){home.style.display="block"}
    else if(hash==="#/about"){about.style.display="block"}
    else{home.style.display="block" }
    // 如果hash为#/home 则显示首页
    // 如果hash值为#/about 则显示关于页面
    // 否则显示首页
})
// 监听hash变化
window.addEventListener("hashchange",e=>{
    let hash = location.hash;
    home.style.display="none";
    about.style.display="none";
    // 默认隐藏首页和about
    if(hash==="#/home"){home.style.display="block"}
    else if(hash==="#/about"){about.style.display="block"}
    else{home.style.display="block" }
})
    

    </script>

</body>
</html>